<?php
class LoginController extends Zend_Controller_Action
{
    public function indexAction() {     
        $form             = new Application_Form_Login();
        $this->view->form = $form;

        if (Zend_Auth::getInstance()->hasIdentity()
            && property_exists(Zend_Auth::getInstance()->getIdentity(), 'role')) {
            $this->_helper->redirector('index', 'content', 'admin');
        }        

        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();

            if ($form->isValid($formData)) {
                $email    = $this->getRequest()->getPost('email');
                $password = $this->getRequest()->getPost('password');

                $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
                $authAdapter->setTableName('user')
                            ->setIdentityColumn('email')
                            ->setCredentialColumn('password');
                            
                $authAdapter->setIdentity($email)
                            ->setCredential(md5($password));                                
                $auth   = Zend_Auth::getInstance();

                $socialId = null;
                if (property_exists($auth->getIdentity(), 'socialId')) 
                    $socialId = $auth->getIdentity()->socialId;                

                $result = $auth->authenticate($authAdapter);

                if ($result->isValid()) {
                    $response = $this->getResponse();
                    $response->setHeader('P3P', 'CP="CAO PSA OUR"', true); 
                    $login               = new Application_Model_Login();
                    //$acl                 = new Application_Model_Acl();                    
                    $user                = $authAdapter->getResultRowObject();                    
                    $role                = $login->getUserRoleById($user->id);                                    

                    $user->role          = $role['role'];
                    $user->departmentIds = $role['department_ids'];
                    $user->roleId        = $role['id'];
                    
                    if ($socialId) {
                        $user->socialId = $socialId;
                    }
                    
                    $authStorage = $auth->getStorage();                    
                    $authStorage->write($user);
                    $dateLogin = date('Y-m-d H:i:s');
                    $login->checkIn($user->id, $dateLogin);
                                        
                    $this->_helper->redirector('index', 'content', 'admin');
                } else {
                    $this->view->message = 'Wrong login or password';
                }
            }
        }       
    }

    public function vkAuthAction() {
        $code = $this->_getParam('code');
        $vk = new My_Vk();
        $accessToken = $vk->getAccessToken($code);
        $loginModel = new Application_Model_Login();        
        if ($loginModel->getUserBySocialId($accessToken['user_id'])) {
            $loginModel->updateSocialUser(
                array(
                    'access_token' => $accessToken['access_token']
                ),
                $accessToken['user_id']
            );
        } else {
            $loginModel->saveSocialUser(
                array(
                    'social_id'    => $accessToken['user_id'],
                    'access_token' => $accessToken['access_token']
                )
            );
        }        
                
        $auth = Zend_Auth::getInstance();                
        if ($auth->hasIdentity()) {
            $userSocial = $auth->getIdentity();            
        } else {
            $userSocial = new stdClass();
        }
        $userSocial->socialId = $accessToken['user_id'];
        $auth->getStorage()->write($userSocial);

        $request = new Zend_Controller_Request_Http();
        $uri = $request->getCookie('redirect_uri');        
        $this->_helper->redirector->gotoUrl($uri);
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index', 'index');
    }
}